/**
 * 价格/数量输入限制
 * Created by 张栋 on 2017/2/16 15:28
 */
;(function ($) {
    $.fn.numInput = function (options) {
        return this.each(function () {
            var $this = $(this);
            var defaults = {
                min:0,//最小值,设置为小数时会存在问题
                max:999999999,//最大值
                maxLength:8,//整数部分最大长度,超长则直接截去
                decimalLength:2//小数部分长度,超长则直接截去,设置为0时,则只能输入整数,不能为小数
            };
            options = options || {};
            var opt = $.extend(defaults, options);
            $this.unbind("keyup");
            $this.keyup(function () {
                var v = $this.val();
                var olength = v.length;
                v = v.replace(/[^\d\.]/g, '')
                    .replace(/^0+/,'0')
                    .replace(/\d*\.\d*/g,function (match,offset) {//处理小数点
                        return ( offset!=0 || opt.decimalLength==0)?match.replace(/\./,''):match.replace(/^\./,'0.');
                    })
                    .replace(/^0+(\d+)/,'$1')
                    .replace(new RegExp("(\\d+\\.\\d{"+opt.decimalLength+"})(\\d)"),'$1')
                    .replace(new RegExp("(\\d{"+opt.maxLength+"})\\d+(\\.\\d*|)"),'$1$2');

                if(v!=""){
                    var vnum =parseFloat(v);
                    if(vnum < opt.min ){
                        v= opt.min;
                    }else if(vnum>opt.max ){
                        v=opt.max;
                    }
                }

                var nlength =v.length;
                if(olength!=nlength){
                    $this.val(v);
                }
            });
        })
    };
})(jQuery);